package com.axjy.config;

import com.baomidou.mybatisplus.extension.plugins.MybatisPlusInterceptor;
import com.baomidou.mybatisplus.extension.plugins.inner.PaginationInnerInterceptor;
import com.baomidou.mybatisplus.extension.spring.MybatisSqlSessionFactoryBean;
import com.zaxxer.hikari.HikariDataSource;
import lombok.SneakyThrows;
import org.mybatis.spring.SqlSessionFactoryBean;
import org.mybatis.spring.annotation.MapperScan;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.ComponentScan;
import org.springframework.context.annotation.Configuration;
import org.springframework.core.io.ClassPathResource;
import org.springframework.core.io.support.PathMatchingResourcePatternResolver;
import org.springframework.core.io.support.ResourcePatternResolver;
import org.springframework.jdbc.datasource.DataSourceTransactionManager;
import org.springframework.transaction.TransactionManager;
import org.springframework.transaction.annotation.EnableTransactionManagement;

import javax.sql.DataSource;

@Configuration
@ComponentScan(basePackages = {"com.axjy.service","com.axjy.config.etc"})
@MapperScan(basePackages = "com.axjy.mapper")
@EnableTransactionManagement //启动事务管理器
public class SpringConfig {

    @Bean
    public DataSource dataSource(){
        HikariDataSource dataSource=new HikariDataSource();
        dataSource.setJdbcUrl("jdbc:mysql://localhost:3306/smbms?serverTimezone=Asia/Shanghai");
        dataSource.setDriverClassName("com.mysql.cj.jdbc.Driver");
        dataSource.setUsername("root");
        dataSource.setPassword("root");
        return dataSource;
    }


    //MyBatis启动对象
    @SneakyThrows
    @Bean
  public MybatisSqlSessionFactoryBean sqlSessionFactoryBean(){
        MybatisSqlSessionFactoryBean sqlSessionFactoryBean=new MybatisSqlSessionFactoryBean();
     sqlSessionFactoryBean.setConfigLocation(new ClassPathResource("mybatis-config.xml"));
     ResourcePatternResolver resourcePatternResolver=new PathMatchingResourcePatternResolver();
     sqlSessionFactoryBean.setMapperLocations(resourcePatternResolver.getResources("classpath:mapper/*.xml"));
     sqlSessionFactoryBean.setDataSource(dataSource());
     sqlSessionFactoryBean.setPlugins(mybatisPlusInterceptor());
     return sqlSessionFactoryBean;
  }

  @Bean
  public TransactionManager transactionManager(){
     DataSourceTransactionManager transactionManager=new DataSourceTransactionManager();
     transactionManager.setDataSource(dataSource());
     return transactionManager;
  }


      @Bean
      public MybatisPlusInterceptor mybatisPlusInterceptor(){
          MybatisPlusInterceptor mybatisPlusInterceptor=new MybatisPlusInterceptor();
          mybatisPlusInterceptor.addInnerInterceptor(new PaginationInnerInterceptor());
          return  mybatisPlusInterceptor;
      }



}
